import os
import datetime

from my_python_tool.utils import pdf_to_images, excel_to_pdf

def excel_to_pdf_and_img():
    """
    Excel转PDF和图片工具
    """
    # 欢迎界面
    print(f"欢迎使用Excel转PDF和图片工具")
    print(f"准备开始转换文件,请确认信息:")
    
    # 获取当前日期字符串
    today = datetime.datetime.now().strftime("%Y%m%d")
    # 校验并创建目录
    souce_path = "./data"
    target_path = "./data/"+today
    if not os.path.exists(target_path):
        os.mkdir(target_path)

    print(f"\n\t当前日期：{today}\n\t文件目录：{souce_path}\n\t输出目录：{target_path}")
    # 获取目标文件夹下的所有excel文件总数
    excel_files = [f for f in os.listdir(souce_path) if f.endswith(".xlsx")]
    if not excel_files:
        print("\n\t当前目录下没有Excel文件")
        exit()
    print(f"\tExcel文件：共找到{len(excel_files)}个")
    # 接收用户输入
    while True:
        choice = input("\n\t是否继续?(y/n): ")
        if choice.lower() in ["y", "n"]:
            break
        else:
            print("\t输入有误，请重新输入")
    # 判断用户选择
    if choice.lower() == "n":
        print("\n\t已取消操作")
        exit()    

    # 定义一个变量，专门记录转换失败的文件信息
    failed_files = []
    for file in excel_files:
        excel_path = os.path.join(souce_path, file)
        pdf_path = os.path.join(target_path, file.replace(".xlsx", ".pdf"))
        img_path = os.path.join(target_path, file.replace(".xlsx", ".png"))
        # 转换成pdf
        print(f"\n\t生成pdf文件中...: {pdf_path}")
        excel_to_pdf(excel_path, pdf_path)
        print(f"\n\t生成图片文件中...: {img_path}")
        rest = pdf_to_images(pdf_path, img_path)
        if rest == None:
            failed_files.append(file)

    print(f"\n\t转换完成！\n\t总计转换文件数：{len(excel_files)}\n\t成功转换文件数：{len(excel_files) - len(failed_files)}\n\t失败转换文件数：{len(failed_files)}")
    if failed_files:
        print(f"\n\t以下文件转换失败：{failed_files}")
    else:
        print(f"\n\t所有文件转换成功！")
    print("\n\t程序结束！")
    exit()